package com.kasinf.sample.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author kaiser
 * @date 2025/6/7
 */
public class NettyServer {
    // 定义线程组：接收客户端连接
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    // 处理已连接客户端的I/O操作
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void start() {
        try {
            // 创建服务器端启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 配置启动参数
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new StringLengthFieldFrameDecoder());

                            // 将 ByteBuf 转换为 String
                            pipeline.addLast(new StringDecoder());

                            // 将 String 转换为 ByteBuf 发送
                            pipeline.addLast(new StringEncoder());

                            // 自定义业务处理器
                            pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                    System.out.println("收到客户端消息: " + msg);
                                    ctx.writeAndFlush("0000000030服务器已收到你的消息");
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    });
            // 绑定端口，启动服务
            ChannelFuture channelFuture = serverBootstrap.bind(14001).sync();
            // 监听关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
